<script setup lang="ts">
import { h, ref, reactive } from "vue"
import {
  FormInst,
  useMessage,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NDataTable,
  NSelect,
  NSwitch,
} from "naive-ui"
import {
  getGoodsList,
  deleteGoods,
  updateGoods,
  createGoods,
  getCateList,
  updateLabel,
  getGoodLabel,
  deleteLabel,
  updateGoodSeckill,
} from "@api/index"
import createGood from "./components/createGoods.vue"
import labelManagement from "./components/labelManagement.vue"
import pagination from "@/components/pagination.vue"
import { getStorage } from "@/util/cache"
const orgId = getStorage("orgId")
const formRef = ref<FormInst | null>(null)
const showModal = ref(false)
const labelShowModal = ref(false)
const message = useMessage()
const editConfig = ref({
  isEdit: false,
  echoData: {},
})
const labelData = ref({})
const formValue = ref({
  key: "",
  catalogId: null,
  showStatus: 1,
})
const pageConfig = ref({
  page: 1,
  pageSize: 10,
})
const pageTotal = ref(0)
const statusOptions = [
  {
    label: "上架中",
    value: 1,
  },
  {
    label: "已下架",
    value: 0,
  },
]

const columns = [
  {
    title: "商品ID",
    key: "orderId",
  },
  {
    title: "商品名字",
    key: "orderName",
  },
  {
    title: "商品类型",
    key: "cateName",
  },
  {
    title: "状态",
    key: "showStatus",
    render(row: any) {
      return row.showStatus === 1 ? "上架中" : "已下架"
    },
  },
  {
    title: "成本价",
    key: "priceCost",
  },
  {
    title: "价格",
    key: "price",
  },
  {
    title: "优惠价",
    key: "priceDiscounts",
  },
  {
    title: "销量",
    key: "saleCount",
  },
  {
    title: "库存",
    key: "stockCount",
  },
  {
    title: "秒杀",
    key: "seckill",
    render(row: any) {
      return [
        h(
          NSwitch,
          {
            value: row.seckill === 1 ? true : false,
            size: "small",
            onUpdateValue: () => {
              const _seckill = row.seckill === 1 ? 0 : 1
              updateGoodSeckill({ seckill: _seckill, orderId: row.orderId }).then((res: any) => {
                if (res.code === 200) {
                  message.success(res.msg)
                } else {
                  message.error(res.msg)
                }
                handleGetGoodsList({
                  limit: pageConfig.value.pageSize,
                  page: pageConfig.value.page,
                  ...formValue.value
                })
              })
            },
          },
          { default: () => "编辑" }
        ),
      ]
    },
  },
  {
    title: "创建时间",
    key: "createTime",
  },
  {
    title: "更新时间",
    key: "updateTime",
  },
  {
    title: "操作",
    key: "action",
    render(row: any) {
      return [
        h(
          NButton,
          {
            size: "small",
            onClick: () => {
              showModal.value = true
              editConfig.value.isEdit = true
              editConfig.value.echoData = row
            },
          },
          { default: () => "编辑" }
        ),
        h(
          NButton,
          {
            size: "small",
            onClick: () => {
              handleDeleteGoods([row?.orderId])
            },
          },
          { default: () => "删除" }
        ),
        h(
          NButton,
          {
            size: "small",
            onClick: () => {
              labelShowModal.value = true
              getGoodLabel({ orderId: row.orderId }).then((res: any) => {
                labelData.value = { orderId: row.orderId, vos: res.data }
              })
            },
          },
          { default: () => "标签管理" }
        ),
      ]
    },
  },
]

const goodsList: any = ref([])
const handleGetGoodsList = (data: any) => {
  getGoodsList({ ...data, orgId }).then((res: any) => {
    goodsList.value = res.data?.list
    pageTotal.value = res.data?.totalCount
  })
}
handleGetGoodsList({
  limit: pageConfig.value.pageSize,
  page: pageConfig.value.page,
  ...formValue.value,
})

const cateList: any = ref([])
getCateList({ orgId }).then((res: any) => {
  cateList.value = res.data.list.map((item: any) => {
    return { label: item.cateName, value: item.cateId }
  })
})

const handleOpenModal = () => {
  showModal.value = true
}

//搜索功能
const handleSearch = () => {
  formRef.value?.validate(errors => {
    if (!errors) {
      handleGetGoodsList({ ...formValue.value, page: 1, limit: 10 })
      pageConfig.value.page = 1
    } else {
      console.log(errors)
    }
  })
}

//弹窗确认
const modalSubmit = (data: any) => {
  // console.log('新增接口调用');
  createGoods({ ...data, orgId }).then((res: any) => {
    if (res.code === 200) {
      message.success(res.msg)
    } else {
      message.error(res.msg)
    }
    handleGetGoodsList({
      limit: pageConfig.value.pageSize,
      page: pageConfig.value.page,
      ...formValue.value,
    })
  })
  showModal.value = false
  editConfig.value.isEdit = false
  editConfig.value.echoData = {}
}
//弹窗关闭
const modalClose = () => {
  showModal.value = false
  editConfig.value.isEdit = false
  editConfig.value.echoData = {}
}
//删除商品
const handleDeleteGoods = (data: any) => {
  deleteGoods(data).then((res: any) => {
    if (res.code === 200) {
      message.success(res.msg)
    } else {
      message.error(res.msg)
    }
    handleGetGoodsList({
      limit: pageConfig.value.pageSize,
      page: pageConfig.value.page,
      ...formValue.value
    })
  })
}

//编辑商品
const handleUpdateGoods = (data: any) => {
  // console.log('编辑接口调用');
  updateGoods(data).then((res: any) => {
    if (res.code === 200) {
      message.success(res.msg)
    } else {
      message.error(res.msg)
    }
    handleGetGoodsList({
      limit: pageConfig.value.pageSize,
      page: pageConfig.value.page,
      ...formValue.value,
    })
    showModal.value = false
    editConfig.value.isEdit = false
    editConfig.value.echoData = {}
  })
}

//编辑商品标签
const handleUpdateLabel = (data: any) => {
  updateLabel(data).then((res: any) => {
    if (res.code === 200) {
      message.success(res.msg)
    } else {
      message.error(res.msg)
    }
    handleGetGoodsList({
      limit: pageConfig.value.pageSize,
      page: pageConfig.value.page,
      ...formValue.value,
    })
    labelShowModal.value = false
  })
}

const labelSubmit = (data: any) => {
  handleUpdateLabel(data)
  labelShowModal.value = false
}

const labelClose = () => {
  labelShowModal.value = false
}

//删除商品标签
const handleDeleteLabel = (id: number) => {
  deleteLabel([id]).then((res: any) => {
    if (res.code === 200) {
      message.success(res.msg)
    } else {
      message.error(res.msg)
    }
  })
}

//分页
const handleChangePage = () => {
  handleGetGoodsList({
    limit: pageConfig.value.pageSize,
    page: pageConfig.value.page,
    ...formValue.value,
  })
}
</script>

<template>
  <div class="index">
    <div class="search">
      <n-form ref="formRef" inline :label-width="80" label-placement="left" :model="formValue">
        <n-form-item label="商品状态" path="showStatus">
          <n-select v-model:value="formValue.showStatus" placeholder="请选择状态" class="form_select" :options="statusOptions"
            clearable />
        </n-form-item>
        <n-form-item label="商品类型" path="catalogId">
          <n-select v-model:value="formValue.catalogId" placeholder="请选择商品类型" class="form_select" :options="cateList"
            clearable />
        </n-form-item>
        <n-form-item label="" path="key">
          <n-input v-model:value="formValue.key" placeholder="模糊搜索" clearable />
        </n-form-item>
        <n-form-item>
          <n-button attr-type="button" @click="handleSearch"> 搜索 </n-button>
        </n-form-item>
      </n-form>
    </div>
    <div class="table">
      <div class="table_action">
        <n-button attr-type="button" @click="handleOpenModal"> 新增商品 </n-button>
      </div>
      <n-data-table :columns="columns" :data="goodsList" :pagination="false" :bordered="false" />
      <pagination :pageTotal="pageTotal" :pageConfig="pageConfig" :handleChangePage="handleChangePage" />
    </div>
    <createGood :handleUpdateGoods="handleUpdateGoods" :showModal="showModal" :modalSubmit="modalSubmit"
      :modalClose="modalClose" :editConfig="editConfig" :cateList="cateList" :statusOptions="statusOptions" />
    <labelManagement :showModal="labelShowModal" :modalSubmit="labelSubmit" :modalClose="labelClose"
      :labelData="labelData" :handleDeleteLabel="handleDeleteLabel" />
  </div>
</template>

<style lang="scss" scoped>
.index {
  overflow-y: scroll; //竖向滚动
  overflow-x: scroll; //横向滚动

  .search {
    height: 90px;
    padding: 20px;
    background-color: var(--BlockBgColor);
    transition: background-color 0.3s var(--n-bezier);
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    .form_select {
      width: 150px;
    }
  }

  .table {
    padding: 20px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    background-color: var(--BlockBgColor);
    transition: background-color 0.3s var(--n-bezier);

    .table_action {
      height: 40px;
      display: flex;
      align-items: center;
    }
  }
}
</style>
